<template>
  <div>
    <el-upload class="upload-oss" drag="drag" :action="uploadUrl" :auto-upload="false" :accept="accept" ref="fileUpload"
      :show-file-list="false" :on-exceed="handleExceed" :on-change="fnUploadChange" :http-request="fnUploadRequest"
      :limit="limit"  :multiple="limit > 1" :disabled="disabled" :file-list="fileList" :before-upload="beforeUpload">
      <slot>
        <i class="el-icon-plus"></i>
      </slot>
    </el-upload>
  </div>
</template>
<script>
import * as message from "@/constants/message";
import * as Constants from "@/constants/constants";
import ComponentApi from "@/api/components/component";

export default {
  name: 'fileUpload',
  props: {
    folder: { // 上传至OSS的文件夹路径
      type: String,
      required: true
    },
    index: { //传过来的索引
      type: Number,
      default: undefined
    },
    param: { //传过来的参数
      type: Object,
      default: undefined
    },
    limit: {
      type: Number,
      default: 1
    },
    accept: {
      type: String,
      default: ".png,.jpg,.jpeg,.bmp"
    }
  },
  data() {
    return {
      imgUrl: "",
      uploadUrl: '#',
      fileList: [],
      uploadHeaders: {
        authorization: ''
      },
      uploadFileList: [],
      chooseFileLength: 0,
      submitLoading: false,
      disabled: false
    }
  },
  watch: {
    uploadFileList() {
      if (this.uploadFileList.length > 0 && this.uploadFileList.length === this.chooseFileLength) {
        // 使用$emit出发父组件的自定义事件
        if (this.index || this.index === 0 || this.param) {
          let rtnObj = { uploadFileList: this.uploadFileList }
          if (this.index || this.index === 0) {
            rtnObj.index = this.index
          }
          if (this.param) {
            rtnObj.param = this.param
          }
          this.$emit('uploadFileList', rtnObj)
        } else {
          this.$emit('uploadFileList', this.uploadFileList)
        }
        this.uploadFileList = []
        this.submitLoading = false
        // clearTimeout(timer);
      }
    },
    limit(limit){
      console.log("限制的个数",limit)
    }
  },
  methods: {
    async fnUploadRequest(option) {
      try {
        const _this = this
        const res = await ComponentApi.uploadOss()
        const ossClient = (await import('ali-oss')).default({
          region: Constants.OSS_REGION,
          accessKeyId: res.data.accessKeyId,
          accessKeySecret: res.data.accessKeySecret,
          stsToken: res.data.securityToken,
          bucket: Constants.OSS_BUCKET
        })
        // 判断已经上传过的不处理--情景：先上传成功3个，后补充1个，之前3个会循环调用。
        if (option && option.response && option.response.url) {
          return
        }
        // 当前上传的文件
        let file = option.file
        const fileName = file.name
        const fileType = fileName.split("\.")[1];
        /*let fileTempName = _this.$Utils.mathRand() + fileName.split("\.")[0];
        if (fileTempName.length > 12){
          fileTempName = fileTempName.substring(0,12);
        }*/
        const newName = _this.$Utils.mathRand19() + "." + fileType;
        const storeAs = Constants.OSS_WEB_URL + _this.folder + '/' + newName;
        //console.log('开始上传，文件名>>>>>' + fileName)
        // TODO 测试 注释上传动作
        ossClient.put(storeAs, file, {}).then(
          function (ret) {
            if (ret.res.statusCode === 200) {
              let realUrl = ret.url.replace(Constants.OSS_URL, Constants.OSS_REAL_URL);
              ret.url = realUrl;
              // _this.uploadFileList = [realUrl]
              _this.uploadFileList.push(realUrl);
              //console.log('上传成功，文件名>>>>>' + fileName)
              //console.log('上传成功，_this.uploadFileList>>>>>' + _this.uploadFileList)
              //option.onSuccess(ret)
              // 值回传
              option.response = ret
              return ret
            } else {
              option.onError('上传失败')
            }
          }
        ).catch(function (err) {
          console.error(err)
        })
      } catch (error) {
        console.error(error)
        this.disabled = false
        option.onError('上传失败')
        this.$error(error.message)
      }
    },

    fnUploadChange(file, fileList) {
      this.chooseFileLength = fileList.length
      this.sureUpload()


    },
    beforeUpload(val) {
      if (val.size / 1024 / 1024 > 5) {
        this.$message.error("大小不能超过5MB")
        return false
      } else {
        return
      }
    },
    handleExceed(list) {
      this.$message.error("最多可以选择" + this.limit + '张图片')
    },
    sureUpload() {

      // return
      let _this = this
      // 判断是否有选择文件
      // if (_this.chooseFileLength == 0){
      //   _this.$message.error('您未选择需上传的文件!')
      //   return
      // }
      _this.submitLoading = true

        _this.$refs.fileUpload.submit()
        _this.$refs.fileUpload.clearFiles()
        // const timer = setTimeout(() => {
        //   // 根据上传个数相等，判断是否已上传完毕
        //   console.log(_this.uploadFileList.length,_this.chooseFileLength)
        //   if (_this.uploadFileList.length > 0 && _this.uploadFileList.length === _this.chooseFileLength) {
        //     // 使用$emit出发父组件的自定义事件
        //     if (_this.index || _this.index === 0 || _this.param) {
        //       let rtnObj = { uploadFileList: this.uploadFileList }
        //       if (_this.index || _this.index === 0) {
        //         rtnObj.index = this.index
        //       }
        //       if (_this.param) {
        //         rtnObj.param = this.param
        //       }
        //       _this.$emit('uploadFileList', rtnObj)
        //     } else {
        //       _this.$emit('uploadFileList', this.uploadFileList)
        //     }
        //     _this.uploadFileList = []
        //     _this.submitLoading = false
        //     clearTimeout(timer);
        //   }
        // }, 500)
      // }).catch(error => {
      //   _this.submitLoading = false
      //   _this.$notify.error({
      //     title: message.TITLE_ERROR,
      //     message: "上传失败，请稍后再试！"
      //   })
      // })

    },
    handleCreate() {
      // 清空旧文件 - 上一次弹窗上传过的文件
      this.fileList = []
      this.uploadFileList = []
    }
  }
}
</script>

<style lang="scss" scoped>
.upload-oss {
  width: 100%;
  max-width: 400px;
  &::v-deep .el-upload {
    width: 100%;
    .el-upload-dragger {
      width: 100%;
      display: flex;
      justify-content: space-around;
      align-items: center;
      .el-icon-plus {
        font-size: 28px;
        color: #8c939d;
        width: 50px;
        height: 50px;
        line-height: 50px;
        text-align: center;
      }
      .tip {
        padding-bottom: 30px;
      }
    }
  }

}

</style>
